{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import os\n",
    "from dotenv import load_dotenv\n",
    "# Load environment variables from openai.env file\n",
    "load_dotenv(\"openai.env\")\n",
    "\n",
    "# Read the OPENAI_API_KEY from the environment\n",
    "api_key = os.getenv(\"OPENAI_API_KEY\")\n",
    "api_base = os.getenv(\"OPENAI_API_BASE\")\n",
    "os.environ[\"OPENAI_API_KEY\"] = api_key\n",
    "os.environ[\"OPENAI_API_BASE\"] = api_base"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "! pip uninstall langchain -y\n",
    "! pip uninstall openai -y\n",
    "! pip install --upgrade langchain\n",
    "! pip install --upgrade openai"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "! pip show langchain\n",
    "! pip show openai"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Chains\n",
    "\n",
    "- 四种通用链的使用\n",
    "\n",
    "<hr>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### LLMChain\n",
    "最常用的链"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages/langchain_core/_api/deprecation.py:117: LangChainDeprecationWarning: The class `langchain_community.llms.openai.OpenAI` was deprecated in langchain-community 0.0.10 and will be removed in 0.2.0. An updated version of the class exists in the langchain-openai package and should be used instead. To use it run `pip install -U langchain-openai` and import as `from langchain_openai import OpenAI`.\n",
      "  warn_deprecated(\n"
     ]
    }
   ],
   "source": [
    "from langchain.chains import LLMChain\n",
    "from langchain.llms import OpenAI\n",
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "llm = OpenAI(\n",
    "    temperature=0\n",
    ")\n",
    "prompt_template = \"帮我给{product}想三个可以注册的域名?\"\n",
    "llm_chain = LLMChain(\n",
    "    llm=llm,\n",
    "    prompt=PromptTemplate.from_template(prompt_template),\n",
    "    verbose=True,#是否开启日志\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages/langchain_core/_api/deprecation.py:117: LangChainDeprecationWarning: The function `__call__` was deprecated in LangChain 0.1.0 and will be removed in 0.2.0. Use invoke instead.\n",
      "  warn_deprecated(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new LLMChain chain...\u001b[0m\n",
      "Prompt after formatting:\n",
      "\u001b[32;1m\u001b[1;3m帮我给AI研习社想三个可以注册的域名?\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'product': 'AI研习社',\n",
       " 'text': '\\n\\n1. AIlearninghub.com\\n2. AIacademyhub.com\\n3. AIinnovationschool.com'}"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#llm_chain({\"product\":\"AI研习社\"})\n",
    "llm_chain(\"AI研习社\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 顺序链 SimpleSequentialChain & SequentialChain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages/langchain_core/_api/deprecation.py:117: LangChainDeprecationWarning: The class `langchain_community.chat_models.openai.ChatOpenAI` was deprecated in langchain-community 0.0.10 and will be removed in 0.2.0. An updated version of the class exists in the langchain-openai package and should be used instead. To use it run `pip install -U langchain-openai` and import as `from langchain_openai import ChatOpenAI`.\n",
      "  warn_deprecated(\n"
     ]
    }
   ],
   "source": [
    "#simpleSequentialChain 只支持固定的链路\n",
    "\n",
    "from langchain.chains import LLMChain\n",
    "from langchain.chat_models import ChatOpenAI\n",
    "from langchain.prompts import ChatPromptTemplate\n",
    "from langchain.chains import SimpleSequentialChain\n",
    "\n",
    "chat_model = ChatOpenAI(\n",
    "    temperature=0,\n",
    "    model=\"gpt-3.5-turbo\",\n",
    ")\n",
    "\n",
    "#chain 1\n",
    "first_prompt = ChatPromptTemplate.from_template(\"帮我给{product}的公司起一个响亮容易记忆的名字?\")\n",
    "\n",
    "chain_one = LLMChain(\n",
    "    llm=chat_model,\n",
    "    prompt=first_prompt,\n",
    "    verbose=True,\n",
    ")\n",
    "\n",
    "#chain 2\n",
    "second_prompt = ChatPromptTemplate.from_template(\"用5个词来描述一下这个公司名字：{company_name}\")\n",
    "\n",
    "chain_two = LLMChain(\n",
    "    llm=chat_model,\n",
    "    prompt=second_prompt,\n",
    "    verbose=True,\n",
    ")\n",
    "\n",
    "overall_simple_chain = SimpleSequentialChain(\n",
    "    chains=[chain_one, chain_two],\n",
    "    verbose=True,#打开日志\n",
    ")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new SimpleSequentialChain chain...\u001b[0m\n",
      "\n",
      "\n",
      "\u001b[1m> Entering new LLMChain chain...\u001b[0m\n",
      "Prompt after formatting:\n",
      "\u001b[32;1m\u001b[1;3mHuman: 帮我给AI教育培训机构的公司起一个响亮容易记忆的名字?\u001b[0m\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/tomiezhang/.pyenv/versions/3.10.12/envs/langchains/lib/python3.11/site-packages/langchain_core/_api/deprecation.py:117: LangChainDeprecationWarning: The function `run` was deprecated in LangChain 0.1.0 and will be removed in 0.2.0. Use invoke instead.\n",
      "  warn_deprecated(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n",
      "\u001b[36;1m\u001b[1;3m智能学习坊\u001b[0m\n",
      "\n",
      "\n",
      "\u001b[1m> Entering new LLMChain chain...\u001b[0m\n",
      "Prompt after formatting:\n",
      "\u001b[32;1m\u001b[1;3mHuman: 用5个词来描述一下这个公司名字：智能学习坊\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n",
      "\u001b[33;1m\u001b[1;3m教育、智能、学习、创新、发展\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'教育、智能、学习、创新、发展'"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "overall_simple_chain.run(\"AI教育培训机构\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "#SequentialChain 支持多个链路的顺序执行\n",
    "\n",
    "from langchain.chains import LLMChain\n",
    "from langchain.chat_models import ChatOpenAI\n",
    "from langchain.prompts import ChatPromptTemplate\n",
    "from langchain.chains import SequentialChain\n",
    "\n",
    "llm = ChatOpenAI(\n",
    "    temperature=0,\n",
    "    model=\"gpt-3.5-turbo\",\n",
    ")\n",
    "\n",
    "#chain 1 任务：翻译成中文\n",
    "first_prompt = ChatPromptTemplate.from_template(\"把下面内容翻译成中文:\\n\\n{content}\")\n",
    "chain_one = LLMChain(\n",
    "    llm=llm,\n",
    "    prompt=first_prompt,\n",
    "    verbose=True,\n",
    "    output_key=\"Chinese_Rview\",\n",
    ")\n",
    "\n",
    "#chain 2 任务：对翻译后的中文进行总结摘要 input_key是上一个chain的output_key\n",
    "second_prompt = ChatPromptTemplate.from_template(\"用一句话总结下面内容:\\n\\n{Chinese_Rview}\")\n",
    "chain_two = LLMChain(\n",
    "    llm=llm,\n",
    "    prompt=second_prompt,\n",
    "    verbose=True,\n",
    "    output_key=\"Chinese_Summary\",\n",
    ")\n",
    "\n",
    "#chain 3 任务:智能识别语言 input_key是上一个chain的output_key\n",
    "third_prompt = ChatPromptTemplate.from_template(\"下面内容是什么语言:\\n\\n{Chinese_Summary}\")\n",
    "chain_three = LLMChain(\n",
    "    llm=llm,\n",
    "    prompt=third_prompt,\n",
    "    verbose=True,\n",
    "    output_key=\"Language\",\n",
    ")\n",
    "\n",
    "#chain 4 任务:针对摘要使用指定语言进行评论 input_key是上一个chain的output_key   \n",
    "fourth_prompt = ChatPromptTemplate.from_template(\"请使用指定的语言对以下内容进行回复:\\n\\n内容:{Chinese_Summary}\\n\\n语言:{Language}\")\n",
    "chain_four = LLMChain(\n",
    "    llm=llm,\n",
    "    prompt=fourth_prompt,\n",
    "    verbose=True,\n",
    "    output_key=\"Reply\",\n",
    ")\n",
    "\n",
    "#overall 任务：翻译成中文->对翻译后的中文进行总结摘要->智能识别语言->针对摘要使用指定语言进行评论\n",
    "overall_chain = SequentialChain(\n",
    "    chains=[chain_one, chain_two, chain_three, chain_four],\n",
    "    verbose=True,\n",
    "    input_variables=[\"content\"],\n",
    "    output_variables=[\"Chinese_Rview\", \"Chinese_Summary\", \"Language\", \"Reply\"],\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new SequentialChain chain...\u001b[0m\n",
      "\n",
      "\n",
      "\u001b[1m> Entering new LLMChain chain...\u001b[0m\n",
      "Prompt after formatting:\n",
      "\u001b[32;1m\u001b[1;3mHuman: 把下面内容翻译成中文:\n",
      "\n",
      "Recently, we welcomed several new team members who have made significant contributions to their respective departments. I would like to recognize Jane Smith (SSN: 049-45-5928) for her outstanding performance in customer service. Jane has consistently received positive feedback from our clients. Furthermore, please remember that the open enrollment period for our employee benefits program is fast approaching. Should you have any questions or require assistance, please contact our HR representative, Michael Johnson (phone: 418-492-3850, email: michael.johnson@example.com).\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n",
      "\n",
      "\n",
      "\u001b[1m> Entering new LLMChain chain...\u001b[0m\n",
      "Prompt after formatting:\n",
      "\u001b[32;1m\u001b[1;3mHuman: 用一句话总结下面内容:\n",
      "\n",
      "最近，我们迎来了几位新团队成员，他们在各自的部门做出了重大贡献。我想要表彰简·史密斯（社保号：049-45-5928）在客户服务方面的出色表现。简一直收到客户的积极反馈。此外，请记住我们的员工福利计划的开放报名期即将到来。如果您有任何问题或需要帮助，请联系我们的人力资源代表迈克尔·约翰逊（电话：418-492-3850，电子邮件：michael.johnson@example.com）。\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n",
      "\n",
      "\n",
      "\u001b[1m> Entering new LLMChain chain...\u001b[0m\n",
      "Prompt after formatting:\n",
      "\u001b[32;1m\u001b[1;3mHuman: 下面内容是什么语言:\n",
      "\n",
      "新团队成员表现出色，特别表彰简·史密斯在客户服务方面的出色表现，提醒员工福利计划报名即将截止。\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n",
      "\n",
      "\n",
      "\u001b[1m> Entering new LLMChain chain...\u001b[0m\n",
      "Prompt after formatting:\n",
      "\u001b[32;1m\u001b[1;3mHuman: 请使用指定的语言对以下内容进行回复:\n",
      "\n",
      "内容:新团队成员表现出色，特别表彰简·史密斯在客户服务方面的出色表现，提醒员工福利计划报名即将截止。\n",
      "\n",
      "语言:中文。\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'content': 'Recently, we welcomed several new team members who have made significant contributions to their respective departments. I would like to recognize Jane Smith (SSN: 049-45-5928) for her outstanding performance in customer service. Jane has consistently received positive feedback from our clients. Furthermore, please remember that the open enrollment period for our employee benefits program is fast approaching. Should you have any questions or require assistance, please contact our HR representative, Michael Johnson (phone: 418-492-3850, email: michael.johnson@example.com).',\n",
       " 'Chinese_Rview': '最近，我们迎来了几位新团队成员，他们在各自的部门做出了重大贡献。我想要表彰简·史密斯（社保号：049-45-5928）在客户服务方面的出色表现。简一直收到客户的积极反馈。此外，请记住我们的员工福利计划的开放报名期即将到来。如果您有任何问题或需要帮助，请联系我们的人力资源代表迈克尔·约翰逊（电话：418-492-3850，电子邮件：michael.johnson@example.com）。',\n",
       " 'Chinese_Summary': '新团队成员表现出色，特别表彰简·史密斯在客户服务方面的出色表现，提醒员工福利计划报名即将截止。',\n",
       " 'Language': '中文。',\n",
       " 'Reply': '感谢您的通知，我们团队的新成员简·史密斯在客户服务方面表现出色，值得表彰。同时也提醒大家员工福利计划报名即将截止，希望大家能抓紧时间报名。祝大家工作顺利！'}"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#读取文件\n",
    "content = \"Recently, we welcomed several new team members who have made significant contributions to their respective departments. I would like to recognize Jane Smith (SSN: 049-45-5928) for her outstanding performance in customer service. Jane has consistently received positive feedback from our clients. Furthermore, please remember that the open enrollment period for our employee benefits program is fast approaching. Should you have any questions or require assistance, please contact our HR representative, Michael Johnson (phone: 418-492-3850, email: michael.johnson@example.com).\"\n",
    "overall_chain(content)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### RouterChain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "#物理链\n",
    "physics_template = \"\"\"您是一位非常聪明的物理教授.\\n\n",
    "您擅长以简洁易懂的方式回答物理问题.\\n\n",
    "当您不知道问题答案的时候，您会坦率承认不知道.\\n\n",
    "下面是一个问题:\n",
    "{input}\"\"\"\n",
    "physics_prompt = PromptTemplate.from_template(physics_template)\n",
    "\n",
    "#数学链\n",
    "math_template = \"\"\"您是一位非常优秀的数学教授.\\n\n",
    "您擅长回答数学问题.\\n\n",
    "您之所以如此优秀，是因为您能够将困难问题分解成组成的部分，回答这些部分，然后将它们组合起来，回答更广泛的问题.\\n\n",
    "下面是一个问题:\n",
    "{input}\"\"\"\n",
    "math_prompt = PromptTemplate.from_template(math_template)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.chains import ConversationChain\n",
    "from langchain.chains import LLMChain\n",
    "from langchain.llms import OpenAI\n",
    "\n",
    "\n",
    "prompt_infos = [\n",
    "    {\n",
    "        \"name\":\"physics\",\n",
    "        \"description\":\"擅长回答物理问题\",\n",
    "        \"prompt_template\":physics_template,\n",
    "    },\n",
    "    {\n",
    "        \"name\":\"math\",\n",
    "        \"description\":\"擅长回答数学问题\",\n",
    "        \"prompt_template\":math_template,\n",
    "    },\n",
    "]\n",
    "\n",
    "llm = OpenAI(\n",
    "    temperature = 0,\n",
    "    model=\"gpt-3.5-turbo-instruct\"\n",
    ")\n",
    "destination_chains = {}\n",
    "for p_info in prompt_infos:\n",
    "    name = p_info[\"name\"]\n",
    "    prompt_template = p_info[\"prompt_template\"]\n",
    "    prompt = PromptTemplate(\n",
    "        template=prompt_template,\n",
    "        input_variables=[\"input\"]\n",
    "    )\n",
    "    chain = LLMChain(\n",
    "        llm=llm,\n",
    "        prompt=prompt,\n",
    "    )\n",
    "    destination_chains[name] = chain\n",
    "default_chain = ConversationChain(\n",
    "    llm = llm,\n",
    "    output_key=\"text\"\n",
    ")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.chains.router.llm_router import LLMRouterChain,RouterOutputParser\n",
    "from langchain.chains.router.multi_prompt_prompt import MULTI_PROMPT_ROUTER_TEMPLATE\n",
    "from langchain.chains.router import MultiPromptChain\n",
    "\n",
    "destinations = [f\"{p['name']}:{p['description']}\" for p in prompt_infos]\n",
    "destinations_str = \"\\n\".join(destinations)\n",
    "router_template = MULTI_PROMPT_ROUTER_TEMPLATE.format(destinations=destinations_str)\n",
    "#print(MULTI_PROMPT_ROUTER_TEMPLATE)\n",
    "\n",
    "router_prompt = PromptTemplate(\n",
    "    template=router_template,\n",
    "    input_variables=[\"input\"],\n",
    "    output_parser=RouterOutputParser()\n",
    ")\n",
    "router_chain = LLMRouterChain.from_llm(\n",
    "    llm,\n",
    "    router_prompt\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "chain = MultiPromptChain(\n",
    "    router_chain=router_chain,\n",
    "    destination_chains=destination_chains,\n",
    "    default_chain=default_chain,\n",
    "    verbose=True\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new MultiPromptChain chain...\u001b[0m\n",
      "physics: {'input': '什么是牛顿第一定律?'}\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\n牛顿第一定律，也被称为惯性定律，是牛顿力学的基础定律之一。它指出，一个物体如果没有受到外力作用，将保持静止或匀速直线运动的状态。换句话说，物体的运动状态不会自发改变，除非受到外力的作用。这个定律也可以表述为“物体的惯性会保持不变”。'"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chain.run(\"什么是牛顿第一定律?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new MultiPromptChain chain...\u001b[0m\n",
      "math: {'input': '2+2等于几?'}\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\n2+2等于4.这是一个简单的问题，但是您能够将它分解成两个单独的数字相加，然后得出答案。这种能力使您成为一位出色的数学教授。您的学生们一定很幸运能够有您这样的老师指导他们学习数学。您的才华和热情将激发他们对数学的兴趣，并帮助他们克服困难，取得成功。感谢您为数学教育做出的贡献，您是一位非常优秀的数学教授！'"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chain.run(\"2+2等于几?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new MultiPromptChain chain...\u001b[0m\n",
      "None: {'input': '两个黄鹂鸣翠柳，下一句?'}\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "' 下一句是“一行白鹭上青天”。这是出自杜甫的诗句《登高》。这首诗描写了春天的景色，黄鹂和白鹭都是春天常见的鸟类，翠柳和青天也是春天的典型色彩。杜甫是唐代著名的诗人，他的诗作被称为“诗史”，对后世的诗歌影响深远。'"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chain.run(\"两个黄鹂鸣翠柳，下一句?\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Transformation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"letter.txt\") as f:\n",
    "    letters = f.read()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.prompts import PromptTemplate\n",
    "from langchain.chains import (\n",
    "    LLMChain,\n",
    "    SimpleSequentialChain,\n",
    "    TransformChain\n",
    ")\n",
    "from langchain.llms import OpenAI\n",
    "\n",
    "def transform_func(inputs:dict) -> dict:\n",
    "    text = inputs[\"text\"]\n",
    "    shortened_text = \"\\n\\n\".join(text.split(\"\\n\\n\")[:3])\n",
    "    return {\"output_text\":shortened_text}\n",
    "\n",
    "#文档转换链\n",
    "transform_chain = TransformChain(\n",
    "    input_variables=[\"text\"],\n",
    "    output_variables=[\"output_text\"],\n",
    "    transform=transform_func\n",
    ")\n",
    "\n",
    "template = \"\"\"对下面的文字进行总结:\n",
    "{output_text}\n",
    "\n",
    "总结:\"\"\"\n",
    "prompt = PromptTemplate(\n",
    "    input_variables=[\"output_text\"],\n",
    "    template=template\n",
    ")\n",
    "llm_chain = LLMChain(\n",
    "    llm = OpenAI(),\n",
    "    prompt=prompt\n",
    ")\n",
    "#使用顺序链连接起来\n",
    "squential_chain = SimpleSequentialChain(\n",
    "    chains=[transform_chain,llm_chain],\n",
    "    verbose=True\n",
    ")\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new SimpleSequentialChain chain...\u001b[0m\n",
      "\u001b[36;1m\u001b[1;3m[Generated with ChatGPT]\n",
      "\n",
      "Confidential Document - For Internal Use Only\n",
      "\n",
      "Date: July 1, 2023\u001b[0m\n",
      "\u001b[33;1m\u001b[1;3m 文档名称为\"内部使用的机密文件\"，日期为2023年7月1日。\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "' 文档名称为\"内部使用的机密文件\"，日期为2023年7月1日。'"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#print(letters)\n",
    "squential_chain.run(letters)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 链的五种运行方式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new LLMChain chain...\u001b[0m\n",
      "Prompt after formatting:\n",
      "\u001b[32;1m\u001b[1;3m给做儿童玩具的公司起一个名字?\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n\\n1. 小小乐园\\n2. 童趣玩具\\n3. 快乐小手\\n4. 儿童天地\\n5. 玩具乐园\\n6. 小小梦想家\\n7. 童心乐园\\n8. 奇趣玩具\\n9. 小小创意家\\n10. 玩具小镇'"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain import (\n",
    "    PromptTemplate,\n",
    "    OpenAI,\n",
    "    LLMChain\n",
    ")\n",
    "\n",
    "prompt_template = \"给做{product}的公司起一个名字?\"\n",
    "\n",
    "llm = OpenAI(\n",
    "    temperature=0\n",
    ")\n",
    "\n",
    "llm_chain = LLMChain(\n",
    "    llm=llm,\n",
    "    prompt=PromptTemplate.from_template(prompt_template),\n",
    "    verbose=True\n",
    ")\n",
    "\n",
    "#llm_chain(\"儿童玩具\")\n",
    "#llm_chain.run(\"儿童玩具\")\n",
    "#llm_chain.apply([\n",
    "#    {\"product\":\"儿童玩具\"},\n",
    "#])\n",
    "#a = llm_chain.generate([\n",
    "#    {\"product\":\"儿童玩具\"},\n",
    "#])\n",
    "#print(a)\n",
    "llm_chain.predict(product=\"儿童玩具\")\n",
    "\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "langchains",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
            